package com.zhj.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * 力扣 3 无重复字符最长字符串
 * @author zhj
 */
public class Test3 {

    public static void main(String[] args) {
        String s = "abcabcbb";
        System.out.println(lengthOfLongestSubstring(s));
    }

    public static int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int r = -1;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (n - i < ans) {
                break;
            }
            if (i != 0) {
                set.remove(s.charAt(i - 1));
            }
            while (r + 1 < n && !set.contains(s.charAt(r + 1))) {
                set.add(s.charAt(r + 1));
                r++;
            }
            ans = Math.max(ans, r - i + 1);
        }
        return ans;
    }
}
